import Scanner from './Scanner'
import nestTokens from "./nestTokens"

/*
* 将模板字符串变成tokens数组
* */
export default function parseTemplateToTokens(templateStr) {
  let tokens = []

  // 创建扫描器
  let scanner = new Scanner(templateStr)
  let words
  while (!scanner.eos()) {
    // 收集开始标记出现的文字
    words = scanner.scanUtil('{{')
    if(words) {
      let isInJJH = false
      // 空白字符串
      let _words = ''
      for(let i = 0; i < words.length; i++) {
        // 判断是否在标签里
        if(words[i] === '<') {
          isInJJH = true
        } else if(words[i] === '>'){
          isInJJH = false
        }
        //如果这项不是空格，拼接上
        if(!/\s/.test(words[i])) {
          _words += words[i]
        } else {
          // 如果这项是空格，只有当它在标签内的时候，拼接上
          if(isInJJH) {
            _words += ' '
          }
        }
      }
      tokens.push(['text', _words])
    }
    // 过双大括号
    scanner.scan('{{')

    words = scanner.scanUtil('}}')
    if(words) {
      if(words[0] === '#') {
        tokens.push(['#', words.substring(1)])
      } else if(words[0] === '/') {
        tokens.push(['/', words.substring(1)])
      } else {
        tokens.push(['name', words])
      }
    }
    scanner.scan('}}')
  }

  // 返回折叠的tokens
  return nestTokens(tokens)
}